//
//  PerMessageDetailsViewController.m
//  sklive
//
//  Created by Macx on 2017/6/29.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "PerMessageDetailsViewController.h"
#import <WebKit/WebKit.h>

@interface PerMessageDetailsViewController ()

@property (nonatomic, strong) WKWebView *webView;

@property (nonatomic, strong) UIProgressView *progressView;

@end

@implementation PerMessageDetailsViewController

- (void)viewWillAppear:(BOOL)animated {
    
    // 获取获取站内信详情
    [self GETMessage];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self buildUI];
    
}

#pragma mark ==========构建UI==========
- (void)buildUI {
    
    self.navigationItem.title = @"消息详情";
    if (!self.mId) {
        self.navigationItem.title = @"平台协议";
    }
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64)];
    if (self.type) {
        self.webView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    }
    [self.view addSubview:self.webView];
    
    //进度条初始化
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, 2)];
//    self.progressView.backgroundColor = RGB(244, 124, 153);
    
    self.progressView.tintColor = RGB(52, 174, 43);
//    self.progressView.trackTintColor = [UIColor whiteColor];
    
    //设置进度条的高度，下面这句代码表示进度条的宽度变为原来的1倍，高度变为原来的1.5倍.
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    [self.view addSubview:self.progressView];
    
    // 1.添加KVO，WKWebView有一个属性estimatedProgress，就是当前网页加载的进度，所以监听这个属性
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
}
// 2.在监听方法中获取网页加载的进度，并将进度赋给progressView.progress
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressView.progress = self.webView.estimatedProgress;
        if (self.progressView.progress == 1) {
            /*
             *添加一个简单的动画，将progressView的Height变为1.4倍，在开始加载网页的代理中会恢复为1.5倍
             *动画时长0.25s，延时0.3s后开始动画
             *动画结束后将progressView隐藏
             */
            __weak typeof (self)weakSelf = self;
            [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                weakSelf.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.4f);
            } completion:^(BOOL finished) {
                weakSelf.progressView.hidden = YES;
                
            }];
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

// 3.在WKWebViewd的代理中展示进度条，加载完成后隐藏进度条
//开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    NSLog(@"开始加载网页");
    //开始加载网页时展示出progressView
    self.progressView.hidden = NO;
    //开始加载网页的时候将progressView的Height恢复为1.5倍
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    //防止progressView被网页挡住
    [self.view bringSubviewToFront:self.progressView];
}

//加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    NSLog(@"加载完成");
    //加载完成后隐藏progressView
    //self.progressView.hidden = YES;
}

//加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    NSLog(@"加载失败");
    //加载失败同样需要隐藏progressView
    //self.progressView.hidden = YES;
}

// 4.在dealloc中取消监听
- (void)dealloc {
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

#pragma mark ==========响应方法==========
/**
 获取站内信详情
 */

- (void)GETMessage {
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    
    [session.requestSerializer setValue:[GetUserDefaule(Token) valueForKey:@"access_token"]forHTTPHeaderField:@"Authorization"];
    
    if (!self.mId) {
        [session GET:APIProtocols parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"获取平台协议 成功 = %@", responseObject);
            
            id obj = [JWT decodeMessage:responseObject[@"token"]].secret(JWTSecret).algorithmName(@"HS256").decode;
            NSLog(@"%@", obj);
            NSDictionary *d = [[obj valueForKey:@"payload"] valueForKey:@"data"];
            
            NSLog(@"%@", d);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self loadContent:d];
                
            });
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }
    else {
        NSString *url = [APIMessages stringByAppendingFormat:@"/%@", self.mId];
        [session GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSLog(@"获取站内信详情 成功 = %@", responseObject);
            
            id obj = [JWT decodeMessage:responseObject[@"token"]].secret(JWTSecret).algorithmName(@"HS256").decode;
            NSLog(@"%@", obj);
            NSDictionary *d = [[obj valueForKey:@"payload"] valueForKey:@"data"];
            
            NSLog(@"%@", d);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [self loadContent:d];
                
            });
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            NSLog(@"获取站内信详情 失败 = %@", error);
            [self presentViewController:[LZCTools AFNErrorAlert:error] animated:YES completion:nil];
        }];
    }
    
    
    
    
}

- (void)loadContent:(NSDictionary *)d {
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    NSMutableString *content;
    
    if (!self.mId) {
        content = [[NSMutableString alloc] initWithString:d[@"body"]];
    }
    else
        content = [[NSMutableString alloc] initWithString:d[@"content"]];
    [content appendString:@"<html>"];
    [content appendString:@"<head>"];
    [content appendString:@"<meta charset=\"utf-8\">"];
    [content appendString:@"<meta id=\"viewport\" name=\"viewport\" content=\"width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=false\" />"];
    [content appendString:@"<meta name=\"apple-mobile-web-app-capable\" content=\"yes\" />"];
    [content appendString:@"<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black\" />"];
    [content appendString:@"<meta name=\"black\" name=\"apple-mobile-web-app-status-bar-style\" />"];
    [content appendString:@"<style>img{width:100%;}</style>"];
    [content appendString:@"<style>table{width:100%;}</style>"];
    [content appendString:@"<title>webview</title>"];
    
    [self.webView loadHTMLString:content baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
